import React, { useState } from 'react';

import classNames from 'classnames';

import { type LazyLoadImageProps, LazyLoadImage } from 'react-lazy-load-image-component';
interface ExtendedImageProps extends Omit<LazyLoadImageProps, 'wrapperClassName'> {
  errorPlaceImg?: boolean;
  imgClassName?: string;
  notShowOnError?: boolean;
  errorClassName?: string;
}
export const NImage = React.memo(
  ({ className, errorPlaceImg, imgClassName, notShowOnError, errorClassName, ...restProps }: ExtendedImageProps) => {
    const [isErrorImg, setIsErrorImg] = useState<boolean>(false);
    return (
      <LazyLoadImage
        {...restProps}
        wrapperClassName={classNames(
          ` !flex flex-center overflow-hidden ${errorPlaceImg && isErrorImg ? 'bg-bgc-6' : ''}`,
          className,
        )}
        className={classNames({
          'size-full': !isErrorImg,
          hidden: isErrorImg && notShowOnError,
          [imgClassName ?? '']: true,
          [errorClassName ?? '']: isErrorImg,
        })}
        onError={(event) => {
          if (isErrorImg) return;
          const img = event.target as HTMLImageElement;
          img.onerror = null;
          img.src = errorPlaceImg ? JL_APP_CONTEXT.source.logo : '';
          img.setAttribute('style', `filter: grayscale(100%); opacity: 0.2;`);
          setIsErrorImg(true);
        }}
      />
    );
  },
);
